import { LogoutOutlined, UserOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import type { MenuProps } from 'antd';
import { Button, Dropdown, message, Space } from 'antd';
import {
  checkTokenUsingPost,
  logoutUsingPost,
} from './services/data-factory/dengluxiaoyanjiekou';

export async function onRouteChange({ location }: { location: any }) {
  const { pathname } = location;
  const token = localStorage.getItem('token');

  // 如果已登录且访问登录页，重定向到首页
  if (token && pathname === '/login') {
    window.location.replace('/home');
    return;
  }

  // 如果未登录且不是登录页，重定向到登录页
  if (!token && pathname !== '/login') {
    window.location.replace('/login');
    return;
  }

  // 如果有 token，验证 token 是否有效
  if (token && pathname !== '/login') {
    try {
      const res = await checkTokenUsingPost();
      if (res.code !== 100200) {
        localStorage.removeItem('token');
        window.location.replace('/login');
      }
    } catch (error) {
      localStorage.removeItem('token');
      window.location.replace('/login');
    }
  }
}

// 添加路由权限配置
export function render(oldRender: () => void) {
  const token = localStorage.getItem('token');
  if (!token && window.location.pathname !== '/login') {
    window.location.replace('/login');
    return;
  }
  oldRender();
}

import type { RequestConfig } from '@umijs/max';

export const request: RequestConfig = {
  timeout: 10000,
  baseURL: '/api', // 添加基础URL配置

  // 请求拦截器
  requestInterceptors: [
    (config: any) => {
      const token = localStorage.getItem('token');

      // 如果有token，添加到请求头
      if (token) {
        config.headers = {
          ...config.headers,
          Authorization: token,
        };
      }

      return config;
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response: any) => {
      const { code } = response.data;

      // 处理token失效的情况
      if (code === 100401 || code === 100403) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('token');
        history.push('/login');
        return Promise.reject(new Error('未登录'));
      }
      return response;
    },
  ],
};
export async function getInitialState(): Promise<{ name: string }> {
  return { name: '@umijs/max' };
}

export const layout = () => {
  return {
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    layout: 'mix',
    menu: {
      locale: false,
    },
    rightRender: () => {
      const account = localStorage.getItem('account');

      const items: MenuProps['items'] = [
        {
          key: 'account',
          label: (
            <div style={{ padding: '8px 16px' }}>
              <div>账号：{account}</div>
            </div>
          ),
        },
        {
          type: 'divider',
        },
        {
          key: 'logout',
          icon: <LogoutOutlined />,
          label: '退出登录',
          onClick: async () => {
            try {
              const res = await logoutUsingPost();
              if (res.code === 100200) {
                message.success('退出登录成功');
                localStorage.removeItem('token');
                localStorage.removeItem('account');
                window.location.href = '/login';
              } else {
                message.error(res.msg || '退出登录失败');
              }
            } catch (error) {
              message.error('退出登录失败');
              localStorage.removeItem('token');
              localStorage.removeItem('account');
              window.location.href = '/login';
            }
          },
        },
      ];

      return (
        <Space style={{ marginRight: 24 }}>
          <Dropdown menu={{ items }} placement="bottomRight">
            <Button type="text" icon={<UserOutlined />} style={{ width: 100 }}>
              <div style={{ width: 100, paddingRight: 20 }}>
                {' '}
                {account || '用户'}
              </div>
            </Button>
          </Dropdown>
        </Space>
      );
    },
  };
};
